var util = require('../../../libs/util.js');
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    name: '',
    address: '',
    show:'false',
    shop_type: ['前置仓', '路边门店', '商场门店', '无人收货门店'],
    shop_type_index: 0,
    form: {
      SHOP_ID:'',
      SH_TIME: '',
      SITE_YTPE:'',
      CENTRE:'',
      C_PHONE:'',
      CONSIGNEE:'',
      PHONE:'',
      ENVIRONMENT:'',
      DISTANCE:'',
      RATIONING: '',
      MAXIMAL: '',
      HASTRAILER: '',
      HASCARRY: '',
      LOCATION:'',
      L_GUIDE:'',
      G_PICTURE:'',
      D_PICTURE:'',
      ZD_PICTURE:'',
      REMARK:''
    },
    G_PICTUREList: [],
    D_PICTUREList: [],
    ZD_PICTUREList: [],
    SH_TIME:'选择收货时间',
    LOCATION: [{ name: '是', value: '1' }, { name: '否', value: '0' }],
    RATIONING: [{ name: '是', value: '1' }, { name: '否', value: '0' }],
    MAXIMAL: [{ name: '是', value: '1' }, { name: '否', value: '0' }],
    HASTRAILER: [{ name: '是', value: '1' }, { name: '否', value: '0' }],
    HASCARRY: [{ name: '是', value: '1' }, { name: '否', value: '0' }]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
     var that = this;
     that.setData({
       id:e.id,
       name:e.name,
       address:e.address,
       show:e.show
     });
    var form = that.data.form;
    form.SHOP_ID = e.id;
    form.SITE_YTPE = that.data.shop_type[that.data.shop_type_index];
    that.setData({
      form: form
    })
    this.initData();
    // this.initValidate()
    // console.log(this.WxValidate)
  },
  initData:function(){
    var that = this;
    util.getData("shopPicture", { 'SHOP_ID': that.data.id}, function (res, error) {
      console.log(error)
      wx.hideLoading();
      console.log(res.data.data)
      if (res.data.success) {
        var data = res.data.data[0];
        that.setData({
          name: data.name,
          address: data.address,
          'form.SH_TIME': data.SH_TIME,
          'form.SITE_YTPE': data.SITE_YTPE,
          'form.CENTRE': data.CENTRE,
          'form.C_PHONE': data.C_PHONE,
          'form.CONSIGNEE': data.CONSIGNEE,
          'form.PHONE': data.PHONE,
          'form.ENVIRONMENT': data.ENVIRONMENT,
          'form.DISTANCE': data.DISTANCE,
          'form.RATIONING': data.RATIONING,
          'form.MAXIMAL': data.MAXIMAL,
          'form.HASTRAILER': data.HASTRAILER,
          'form.HASCARRY': data.HASCARRY,
          'form.LOCATION': data.LOCATION,
          'form.L_GUIDE': data.L_GUIDE,
          'form.G_PICTURE': data.G_PICTURE,
          'form.D_PICTURE': data.D_PICTURE,
          'form.ZD_PICTURE': data.ZD_PICTURE,
          'form.REMARK': data.REMARK
        });
        var LOCATION = that.data.LOCATION;
        for (var i = 0; i < LOCATION.length;i++){
          if (LOCATION[i].value == data.LOCATION){
            LOCATION[i].checked = true;
          }
        }
        that.setData({
          LOCATION: LOCATION
        })
        var RATIONING = that.data.RATIONING;
        for (var i = 0; i < RATIONING.length; i++) {
          if (RATIONING[i].value == data.RATIONING) {
            RATIONING[i].checked = true;
          }
        }
        that.setData({
          RATIONING: RATIONING
        })
        var MAXIMAL = that.data.MAXIMAL;
        for (var i = 0; i < MAXIMAL.length; i++) {
          if (MAXIMAL[i].value == data.MAXIMAL) {
            MAXIMAL[i].checked = true;
          }
        }
        that.setData({
          MAXIMAL: MAXIMAL
        })
        var HASTRAILER = that.data.HASTRAILER;
        for (var i = 0; i < HASTRAILER.length; i++) {
          if (HASTRAILER[i].value == data.HASTRAILER) {
            HASTRAILER[i].checked = true;
          }
        }
        that.setData({
          HASTRAILER: HASTRAILER
        })
        var HASCARRY = that.data.HASCARRY;
        for (var i = 0; i < HASCARRY.length; i++) {
          if (HASCARRY[i].value == data.HASCARRY) {
            HASCARRY[i].checked = true;
          }
        }
        that.setData({
          HASCARRY: HASCARRY
        })
        that.setData({
          SH_TIME: data.SH_TIME
        });
        that.setData({
          shop_type_index: that.data.shop_type.indexOf(data.SITE_YTPE)
        })
        if (data.G_PICTURE != '') {
          that.setData({
            G_PICTUREList: data.G_PICTURE.split(",")
          })
        }
        if (data.D_PICTURE != '') {
          that.setData({
            D_PICTUREList: data.D_PICTURE.split(",")
          })
        }
        if (data.ZD_PICTURE != '') {
          that.setData({
            ZD_PICTUREList: data.ZD_PICTURE.split(",")
          })
        }
      }else{
        if (that.data.show) {
          wx.showModal({
            title: '温馨提示',
            content: '抱歉，暂无本门店勘察信息，我们的勘察员正在快马加鞭的勘察中...',
            success(res) {
              wx.navigateBack({
                delta: 1
              })
            }
          })
        }
      }
    });
  },
  bindTimeChange: function (e) {
    var form = this.data.form;
    form.SH_TIME = e.detail.value;
    this.setData({
      form: form,
      SH_TIME: e.detail.value
    })
  },
  bindPickerChange: function (e) {
    this.setData({
      shop_type_index: e.detail.value
    })
    var form = this.data.form;
    form.SITE_YTPE = this.data.shop_type[e.detail.value];
    this.setData({
      form: form
    })
  },
  bindFormInput:function(e){
    var that = this;
    var item = String(e.currentTarget.id), item_value = {};
    var form = that.data.form;
    form[item] = e.detail.value;
    that.setData({
      form: form
    });
  },
  handleTypeChange: function (e) {
    var that = this;
    var item = String(e.currentTarget.id), item_value = {};
    var form = that.data.form;
    form[item] = e.detail.value;
    that.setData({
      form: form
    });
    var data = that.data[item];
    console.log(data)
  },
  deleteImage: function (e) {
    var that = this;
    var url = e.currentTarget.dataset.src;
    util.putData("deleteFile", { url: url}, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
        return false;
      }
      if (res.data.success) {
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 2000
        })
        var G_PICTUREList = that.data.G_PICTUREList, D_PICTUREList = that.data.D_PICTUREList, ZD_PICTUREList = that.data.ZD_PICTUREList;
        var _G_PICTUREList = [], _D_PICTUREList = [], _ZD_PICTUREList = [];
        var is_find = false;
        for (var i = 0; i < G_PICTUREList.length;i++){
          if (G_PICTUREList[i] == url){
            is_find = true;
            that.setData({
              'form.G_PICTURE': that.data.form.G_PICTURE.replace(url, '').replace(',,', '')
            })
          }else{
            _G_PICTUREList.push(G_PICTUREList[i]);
          }
        }
        that.setData({
          G_PICTUREList: _G_PICTUREList
        })
        if (is_find) return;
        for (var i = 0; i < D_PICTUREList.length; i++) {
          if (D_PICTUREList[i] == url) {
            is_find = true;
            that.setData({
              'form.D_PICTURE': that.data.form.D_PICTURE.replace(url, '').replace(',,', '')
            })
          } else {
            _D_PICTUREList.push(D_PICTUREList[i]);
          }
        }
        that.setData({
          D_PICTUREList: _D_PICTUREList
        })
        if (is_find) return;
        for (var i = 0; i < ZD_PICTUREList.length; i++) {
          if (ZD_PICTUREList[i] == url) {
            is_find = true;
            that.setData({
              'form.ZD_PICTURE': that.data.form.ZD_PICTURE.replace(url, '').replace(',,', '')
            })
          } else {
            _ZD_PICTUREList.push(ZD_PICTUREList[i]);
          }
        }
        that.setData({
          ZD_PICTUREList: _ZD_PICTUREList
        })
      } else {
        wx.showToast({ title: '删除失败', image: '/images/wrong.svg', duration: 2000 });
      };
    });
  },
  chooseG_PICTUREImage: function () {
    var that = this;
    var G_PICTUREList = that.data.G_PICTUREList;
    if (G_PICTUREList.length == 5) {
      wx.showToast({
        title: "最多5张照片",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    }
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res)
        wx.showLoading({
          title: '上传中...'
        });
        wx.uploadFile({
          url: app.server + '/wechat/wxapplet/uploadSiteInfoImage',
          header:{
            'Authorization': app.globalData.token
          },
          filePath: res.tempFilePaths[0],
          name: 'file',
          formData: {
            'id': that.data.id
          },
          success: function (res) {
            var data = JSON.parse(res.data); console.log(data)
            if (data.success) {
              G_PICTUREList.push(app.server + data.data[0].path);
              that.setData({
                G_PICTUREList: G_PICTUREList
              });
              var form = that.data.form;
              form.G_PICTURE = G_PICTUREList.join(',');
              that.setData({
                form: form
              })
            } else {
              wx.showToast({
                title: "上传失败",
                image: '/images/wrong.png',
                duration: 2000
              });
            }
          },
          complete: function () {
            wx.hideLoading();
          }
        })
      }
    })
  },
  previewG_PICTUREImage: function (e) {
    var current = e.target.dataset.src

    wx.previewImage({
      current: current,
      urls: this.data.G_PICTUREList
    })
  },
  chooseD_PICTUREImage: function () {
    var that = this;
    var D_PICTUREList = that.data.D_PICTUREList;
    if (D_PICTUREList.length == 5) {
      wx.showToast({
        title: "最多5张照片",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    }
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res)
        wx.showLoading({
          title: '上传中...'
        });
        wx.uploadFile({
          url: app.server + '/wechat/wxapplet/uploadSiteInfoImage',
          header:{
            'Authorization': app.globalData.token
          },
          filePath: res.tempFilePaths[0],
          name: 'file',
          formData: {
            'id': that.data.id
          },
          success: function (res) {
            var data = JSON.parse(res.data); console.log(data)
            if (data.success) {
              D_PICTUREList.push(app.server + data.data[0].path);
              that.setData({
                D_PICTUREList: D_PICTUREList
              });
              var form = that.data.form;
              form.D_PICTURE = D_PICTUREList.join(',');
              that.setData({
                form: form
              })
            } else {
              wx.showToast({
                title: "上传失败",
                image: '/images/wrong.png',
                duration: 2000
              });
            }
          },
          complete: function () {
            wx.hideLoading();
          }
        })
      }
    })
  },
  previewD_PICTUREImage: function (e) {
    var current = e.target.dataset.src

    wx.previewImage({
      current: current,
      urls: this.data.D_PICTUREList
    })
  },
  chooseZD_PICTUREImage: function () {
    var that = this;
    var ZD_PICTUREList = that.data.ZD_PICTUREList;
    if (ZD_PICTUREList.length == 5) {
      wx.showToast({
        title: "最多5张照片",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    }
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res)
        wx.showLoading({
          title: '上传中...'
        });
        wx.uploadFile({
          url: app.server + '/wechat/wxapplet/uploadSiteInfoImage',
          header:{
            'Authorization': app.globalData.token
          },
          filePath: res.tempFilePaths[0],
          name: 'file',
          formData: {
            'id': that.data.id
          },
          success: function (res) {
            var data = JSON.parse(res.data); console.log(data)
            if (data.success) {
              ZD_PICTUREList.push(app.server + data.data[0].path);
              that.setData({
                ZD_PICTUREList: ZD_PICTUREList
              });
              var form = that.data.form;
              form.ZD_PICTURE = ZD_PICTUREList.join(',');
              that.setData({
                form: form
              })
            } else {
              wx.showToast({
                title: "上传失败",
                image: '/images/wrong.png',
                duration: 2000
              });
            }
          },
          complete: function () {
            wx.hideLoading();
          }
        })
      }
    })
  },
  previewZD_PICTUREImage: function (e) {
    var current = e.target.dataset.src

    wx.previewImage({
      current: current,
      urls: this.data.ZD_PICTUREList
    })
  },
  submitForm(e) {
    var that = this;
    var params = e.detail.value

    console.log(params)

    // 传入表单数据，调用验证方法
    // if (!that.WxValidate.checkForm(params)) {
    //   var error = that.WxValidate.errorList[0];
    //   wx.showModal({
    //     content: error.msg
    //   })
    //   return false
    // }
    var data = that.data.form;
    util.postData("shopPicture", data, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({ title: '更新失败', image: '/images/wrong.svg', duration: 2000 });
        return false;
      }
      if (res.data.success) {
        //轨迹
        wx.showModal({
          title: "温馨提示",
          content: "门店画像已提交成功",
          confirmText: "继续编辑",
          cancelText:"门店列表",
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '/pages/schedule/apps/shopPicture?id=' + that.data.id + '&name=' + that.data.name+'&address=' + that.data.address
              });
            } else if (res.cancel) {
              wx.redirectTo({
                url: '/pages/schedule/shop'
              });
            }
          }
        });
      } else {
        wx.showToast({ title: '更新失败', image: '/images/wrong.svg', duration: 2000 });
      };
    });
  },
  initValidate() {
    // 验证字段的规则
    const rules = {
      SITE_YTPE: {
        required: true
      },
      SH_TIME: {
        required: true
      },
      CENTRE: {
        required: true
      },
      C_PHONE: {
        required: true
      },
      CONSIGNEE: {
        required: true
      },
      PHONE: {
        required: true
      },
      ENVIRONMENT: {
        required: true
      },
      DISTANCE: {
        required: true,
      },
      RATIONING: {
        required: true
      },
      MAXIMAL: {
        required: true,
      },
      HASTRAILER: {
        required: true
      },
      HASCARRY: {
        required: true
      },
      LOCATION: {
        required: true
      },
      L_GUIDE: {
        required: true
      },
      G_PICTURE: {
        required: true
      },
      D_PICTURE: {
        required: true
      },
      ZD_PICTURE: {
        required: true
      },
      REMARK: {
        required: true
      }
    }

    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      SITE_YTPE: {
        required: '请选择站点类型'
      },
      SH_TIME: {
        required: '请选择收货时间'
      },
      CENTRE: {
        required: '请输入站长姓名'
      },
      C_PHONE: {
        required: '请输入站长手机号码'
      },
      CONSIGNEE: {
        required: '请输入收货人姓名'
      },
      PHONE: {
        required: '请输入收货人手机号码'
      },
      ENVIRONMENT: {
        required: '请输入站点周围环境描述'
      },
      DISTANCE: {
        required: '请输入停车位置到站点的距离',
      },
      RATIONING: {
        required: '请选择站点经过的路是否限制宽度'
      },
      MAXIMAL: {
        required: '请选择站点经过的路是否限制高度',
      },
      HASTRAILER: {
        required: '请选择站点收拖车提供'
      },
      HASCARRY: {
        required: '请选择站点是否帮忙搬货'
      },
      LOCATION: {
        required: '请选择定位是否在站点门口'
      },
      L_GUIDE: {
        required: '请输入定位点到达站点的指引'
      },
      G_PICTURE: {
        required: '请上传定位点到达站点的指引图片'
      },
      D_PICTURE: {
        required: '请上传停车位置指引图片'
      },
      ZD_PICTURE: {
        required: '请上传站点门口图片'
      },
      REMARK: {
        required: '请输入站点画像的其他描述'
      }
    }

    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages)
  },
  backToShopList:function(){
    if (this.data.show == 'true'){
      wx.navigateBack({
        delta: 1
      })
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '确认返回门店列表，改变的门店画像信息将丢失',
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '/pages/schedule/shop'
            })
          }
          if (res.cancel) {

          }
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})